package com.xuanzheng.company.servlet;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.xuanzheng.company.entity.Task;
import com.xuanzheng.company.entity.User;
import com.xuanzheng.company.service.TaskService;
import com.xuanzheng.company.service.impl.TaskServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.stream.Collectors;

@WebServlet("/api/tasks")
public class GetTasksServlet extends HttpServlet {
    private final TaskService taskService = new TaskServiceImpl();
    private final Gson gson = new Gson();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        JsonObject result = new JsonObject();

        try {
            System.out.println("GetTasksServlet: 开始处理请求");
            
            // 检查用户是否登录
            HttpSession session = req.getSession();
            User user = (User) session.getAttribute("user");
            if (user == null) {
                System.out.println("GetTasksServlet: 用户未登录");
                result.addProperty("success", false);
                result.addProperty("message", "请先登录");
                out.print(gson.toJson(result));
                return;
            }
            
            System.out.println("GetTasksServlet: 当前用户ID=" + user.getId() + ", 姓名=" + user.getName() + ", 公司ID=" + user.getCompanyId());

            // 获取状态过滤参数
            String statusParam = req.getParameter("status");
            Integer statusFilter = null;
            if (statusParam != null && !statusParam.isEmpty()) {
                try {
                    statusFilter = Integer.parseInt(statusParam);
                    System.out.println("GetTasksServlet: 状态过滤 status=" + statusFilter);
                } catch (NumberFormatException e) {
                    System.out.println("GetTasksServlet: 无效的状态参数: " + statusParam);
                }
            }

            List<Task> tasks;
            String type = req.getParameter("type");
            System.out.println("GetTasksServlet: 请求类型type=" + type);

            if ("employee".equals(type)) {
                // 获取员工的任务
                System.out.println("GetTasksServlet: 获取员工的任务，员工ID=" + user.getId());
                tasks = taskService.getTasksByEmployeeId(user.getId());
            } else if ("manager".equals(type)) {
                // 获取管理者派发的任务
                System.out.println("GetTasksServlet: 获取管理者派发的任务，管理者ID=" + user.getId());
                tasks = taskService.getTasksByManagerId(user.getId());
            } else if ("company".equals(type) && user.getRole() == 1) {
                // 获取公司所有任务（仅限公司负责人）
                System.out.println("GetTasksServlet: 获取公司所有任务，公司ID=" + user.getCompanyId());
                tasks = taskService.getTasksByCompanyId(user.getCompanyId());
            } else {
                System.out.println("GetTasksServlet: 无效的请求类型type=" + type);
                result.addProperty("success", false);
                result.addProperty("message", "无效的请求类型");
                out.print(gson.toJson(result));
                return;
            }
            
            System.out.println("GetTasksServlet: 获取到任务数量：" + (tasks != null ? tasks.size() : "null"));

            // 根据状态过滤任务
            if (statusFilter != null && statusFilter >= 0 && tasks != null) {
                final int status = statusFilter;
                tasks = tasks.stream()
                        .filter(task -> task.getStatus() == status)
                        .collect(Collectors.toList());
                System.out.println("GetTasksServlet: 过滤后任务数量：" + tasks.size());
            }

            result.addProperty("success", true);
            result.add("tasks", gson.toJsonTree(tasks));
        } catch (Exception e) {
            System.out.println("GetTasksServlet: 发生错误：" + e.getMessage());
            e.printStackTrace();
            result.addProperty("success", false);
            result.addProperty("message", "系统错误: " + e.getMessage());
        }

        out.print(gson.toJson(result));
        System.out.println("GetTasksServlet: 请求处理完成");
    }
} 